package cskevin.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;
/**
 * 锟斤拷装锟斤拷SDCard锟斤拷锟斤拷
 * 2013.2
 * @author csKevin
 * */
public class SDUtils{
	
	private String SDPATH;

	public SDUtils(){//锟斤拷锟斤拷锟叫筹拷始锟斤拷sdCard锟侥憋拷锟斤拷值		
		SDPATH=Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
	}
	public String getSDPath(){//锟矫碉拷sdCard锟斤拷路锟斤拷
		return SDPATH;
	}
	/**
	 *锟斤拷锟斤拷一锟斤拷锟侥硷拷file
	 *@throws IOException
	 * */
	public File createSDFile(String fileName) throws IOException{
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}
	/**
	 *锟斤拷SD锟斤拷锟较达拷锟斤拷一锟斤拷锟侥硷拷目录 锟斤拷
	 *@param dirName
	 */
	public File createSDdir(String dirName){
		File fileDir = new File(SDPATH + dirName);
		fileDir.mkdirs();
		return fileDir;	
	}
	/**
	 * 锟叫讹拷SD锟斤拷锟斤拷锟侥硷拷锟角凤拷锟斤拷锟�
	 * @param fileName
	 * */
	public boolean isFileExist(String fileName){
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	/**
	 * 锟叫讹拷锟侥硷拷目录锟角凤拷锟斤拷锟�
	 * */
	public boolean isDirExist(String dirName){
		File fileDir = new File(SDPATH + dirName);
		return fileDir.exists();
		
	}
	/**
	 * 锟斤拷一锟斤拷InputStream写锟诫到sd锟斤拷锟斤拷
	 * @param fileName
	 * @param sdPath
	 * @param input
	 * @param isFileExist
	 * */
	public  File toSDfromInputSteam(String fileName,String sdPath,
			InputStream input){
		File file=null;
		OutputStream outputStream=null;
		try{
				createSDdir(sdPath);
				file = createSDFile(sdPath+File.separator+fileName);
				outputStream = new FileOutputStream(file);
				byte[] buffer = new byte[4*1024];
				int temp;
				while((temp = input.read(buffer)) != -1){
					outputStream.write(buffer,0,temp);
				}
			outputStream.flush();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				outputStream.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return file;
	}
}